package crowx.android.AndCellTrack;

import crowx.android.AndCellTrack.logger.Logger;
import android.content.ContextWrapper;
import android.content.Intent;
import android.telephony.ServiceState;
import android.telephony.gsm.GsmCellLocation;

public class AndCellTrackService extends AndCellTrackServiceBase {
	private Logger logger = null;
	
	public static void startService(ContextWrapper context) {
		android.util.Log.d(TAG, "AndCellTrack.startService");
		Intent i = new Intent();
	    i.setClassName( "crowx.android.AndCellTrack","crowx.android.AndCellTrack.AndCellTrackService" );
	    context.startService(i);	    
	}
	
	public static void stopService(ContextWrapper context) {
		android.util.Log.d(TAG, "AndCellTrack.stopService");
		Intent i = new Intent();
		i.setClassName( "crowx.android.AndCellTrack","crowx.android.AndCellTrack.AndCellTrackService" );
		context.stopService(i);		
	}
	
	@Override
	public void onCreate() {
		super.onCreate();
		logger = new Logger();
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		logger.close();
	}
	
	@Override
	protected void onCellLocationChanged(GsmCellLocation location, int networkType) {
		android.util.Log.d(TAG, "AndCellTrackService.onCellLocationChanged");
		cellInfo.setLAC(location.getLac());
		cellInfo.setLCID(location.getCid());
		cellInfo.netType = networkType;
		
		cellTrackStateObservable.onStateChanged(cellInfo);
		logger.logCell(cellInfo);
	}

	@Override
	protected void onServiceStateChanged(ServiceState serviceState,	GsmCellLocation location, int networkType) {
		android.util.Log.d(TAG, "AndCellTrackService.onServiceStateChanged");
		cellInfo.netName = serviceState.getOperatorAlphaLong();
		int net;
		try {
			net = Integer.parseInt(serviceState.getOperatorNumeric());
		}
		catch(NumberFormatException e) {
			net = -1;
		}
		cellInfo.setMCCMNC(net);
		cellInfo.netState = serviceState.getState();
		cellInfo.netCountryIso = telephonyManager.getNetworkCountryIso().toUpperCase();
		
		onCellLocationChanged(location,networkType);
	}

	@Override
	protected void onSignalStrengthChanged(int asu) {
		android.util.Log.d(TAG, "AndCellTrackService.onSignalStrengthChanged");
		cellInfo.setRXLAsu(asu);
		
		cellTrackStateObservable.onStateChanged(cellInfo);
		logger.logCell(cellInfo);
	}
}
